/*
	weak_type_mempool.h
	@author:Wolfhead
*/
#ifndef WOLV_WEAK_TYPE_MEMPOOL_HPP
#define WOLV_WEAK_TYPE_MEMPOOL_HPP

namespace wolv
{
namespace weakType
{
namespace allocator
{

template<int size>
class MemPool
{
public:
	static MemPool<size>& Instance()
	{
		static MemPool<size> instance_;
		return instance_;
	}

	void * alloc();
	void release(void * p);

private:
	MemPool();
	~MemPool();

	void _initPool();
	void _releasePool();

	MemPool(const MemPool&);
	MemPool& operator= (const MemPool&);

	int* head;


};

template<int size>
MemPool<size>::MemPool()
{
	_initPool();
}

template<int size>
MemPool<size>::~MemPool()
{
	_releasePool();
}

template<int size>
void * MemPool<size>::alloc()
{
	if (head == 0)
	{
		return new char[size];
	}
	else
	{
		int * p = head;
		head = (int*)*p;
		return p;
	}
}

template<int size>
void MemPool<size>::release( void * p )
{
	union cast
	{
		int to;
		int * from;
	}cast_;
	cast_.from = head;
	*(static_cast<int*>(p)) = cast_.to;
	head = (int*)p;
	return;
}


template<int size>
void MemPool<size>::_initPool()
{
	head = 0;
	return;
}

template<int size>
void MemPool<size>::_releasePool()
{
	char * next, *p;
	next = p = (char*)(head);
	while (next) {
		next = (char*)*(int*)p;
		delete [] p;
		p = next;
	}

}


}//namespace allocator
}//namespace weakType
}//namepsace wolv



#endif
